<template>
  <div>
    <my-breadcrumb :items="['商品管理', '商品属性']"></my-breadcrumb>
    <Row>
      <i-col span="8">
        <h3>商品分类（后面括号为权重）</h3>
        <Tree :data="treeClassifyData" children-key="childCategoryList"/>
      </i-col>
      <i-col span="8">
        <h3>商品单位</h3>
        <ul class="list">
          <li>
            <Button type="dashed" @click="addUnit">+添加单位</Button>
          </li>
          <li v-for="(unit, index) in units" :key="index">
            <span>{{ unit.unit }}</span>
            <div class="icon_box">
              <Icon type="close-circled" size="12" color="#ed3f14" @click="delUnit(unit.id)"></Icon>
              <Icon type="edit" size="12" color="#2b85e4" @click="updateUnit(unit.id, unit.unit)"></Icon>
            </div>
          </li>
        </ul>
      </i-col>
      <i-col span="8">
        <h3>商品标签</h3>
        <ul class="list">
          <li>
            <Button type="dashed" @click="addLabel">+添加标签</Button>
          </li>
          <li v-for="(label, index) in labels" :key="index">
            <span>{{ label.label }}</span>
            <div class="icon_box">
              <Icon type="close-circled" size="12" color="#ed3f14" @click="delLabel(label.id)"></Icon>
              <Icon type="edit" size="12" color="#2b85e4" @click="updateLabel(label.id, label.label)"></Icon>
            </div>
          </li>
        </ul>
      </i-col>
    </Row>
    <Modal
      v-model="modal"
      title="添加分类"
      @on-ok="subAddClassify"
      :mask-closable="false">
      <Form :model="form" :label-width="70" :rules="formRules" ref="form">
        <FormItem label="分类名称" prop="name">
          <Input v-model="form.name" placeholder="这个分类叫什么..." />
        </FormItem>
        <FormItem label="分类描述" prop="description">
          <Input v-model="form.description" placeholder="描述一下这个分类..." />
        </FormItem>
        <FormItem label="分类权重" prop="sortWeight">
          <InputNumber v-model="form.sortWeight" :min="0" :max="100"/>
          <span>分类权重，分类排序依据</span>
        </FormItem>
      </Form>
    </Modal>
    <Modal
      v-model="updateModal"
      title="添加分类"
      @on-ok="subUpdate"
      :mask-closable="false">
      <Form :model="updateForm" :label-width="70" :rules="formRules" ref="updateForm">
        <FormItem label="分类名称" prop="name">
          <Input v-model="updateForm.name" placeholder="这个分类叫什么..." />
        </FormItem>
        <FormItem label="分类描述" prop="description">
          <Input v-model="updateForm.description" placeholder="描述一下这个分类..." />
        </FormItem>
        <FormItem label="分类权重" prop="sortWeight">
          <InputNumber v-model="updateForm.sortWeight" :min="0" :max="100"/>
          <span>分类权重，分类排序依据</span>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
export default {
  name: 'goods-classify',
  data () {
    let validateChinese = (rule, value, callback) => {
      if (!(/^[0-9a-zA-Z\u4e00-\u9fa5_-]{1,20}$/.test(value))) {
        callback(new Error('只能有中文数字字母下划线、‘-’'))
      } else {
        callback()
      }
    }
    let first = (h, { root, node, data }) => {
      return h('span', {
        style: {
          display: 'inline-block',
          width: '100%',
          fontSize: '14px',
          color: '#495060'
        },
        'class': {
          hoverShow: true
        }
      }, [
        h('span', [
          h('Icon', {
            props: {
              type: 'plus-round'
            },
            style: {
              marginRight: '8px',
              cursor: 'pointer'
            },
            on: {
              click: () => { this.appendFirstClassify(data) }
            }
          }),
          h('span', data.title + '(' + data.sortWeight + ')'),
          h('span', {
            'class': {
              showClassify: true
            }
          }, [
            h('span', {
              style: {
                marginLeft: '16px',
                color: '#2b85e4',
                cursor: 'pointer'
              },
              on: {
                click: () => {
                  this.firstUpdate(data)
                }
              }
            }, '修改'),
            h('span', {
              style: {
                marginLeft: '16px',
                color: '#ed3f14',
                cursor: 'pointer'
              },
              on: {
                click: () => {
                  this.removeClassify(data)
                }
              }
            }, '删除')
          ])
        ])
      ])
    }
    let second = (h, { root, node, data }) => {
      return h('span', {
        style: {
          fontSize: '14px',
          color: '#80848f'
        },
        'class': {
          hoverShow: true
        }
      }, [
        h('span', {
          style: {
            marginLeft: '10px'
          }
        }, data.title + '(' + data.sortWeight + ')'),
        h('span', {
          'class': {
            showClassify: true
          }
        }, [
          h('span', {
            style: {
              marginLeft: '16px',
              color: '#2b85e4',
              cursor: 'pointer'
            },
            on: {
              click: () => {
                this.firstUpdate(data)
              }
            }
          }, '修改'),
          h('span', {
            style: {
              marginLeft: '16px',
              color: '#ed3f14',
              cursor: 'pointer'
            },
            on: {
              click: () => {
                this.removeClassify(data)
              }
            }
          }, '删除')
        ])
      ])
    }
    return {
      modal: false,
      form: {
        name: '',
        description: '',
        sortWeight: 0
      },
      formRules: {
        name: [
          { required: true, message: '名字不能为空', trigger: 'blur' },
          { validator: validateChinese, trigger: 'blur' }
        ]
      },
      treeClassifyData: [
        {
          title: '所有分类',
          expand: true,
          render: (h, { root, node, data }) => {
            return h('span', {
              style: {
                display: 'inline-block',
                width: '100%',
                fontSize: '16px'
              }
            }, [
              h('span', [
                h('Icon', {
                  props: {
                    type: 'plus-round'
                  },
                  style: {
                    marginRight: '8px',
                    cursor: 'pointer'
                  },
                  on: {
                    click: () => { this.appendFirstClassify(data) }
                  }
                }),
                h('span', data.title)
              ])
            ])
          },
          childCategoryList: []
        }
      ],
      first: first,
      second: second,
      nodeData: null,
      updateForm: {
        id: null,
        name: '',
        description: '',
        sortWeight: null
      },
      updateModal: false,
      oldData: '',

      // 单位标签
      units: [],
      labels: []
    }
  },
  methods: {
    firstUpdate (data) {
      this.updateModal = true
      this.updateForm.id = data.id
      this.updateForm.name = data.name
      this.updateForm.description = data.description
      this.updateForm.sortWeight = data.sortWeight
      this.oldData = JSON.stringify(this.updateForm)
    },
    subUpdate () {
      this.$refs.updateForm.validate((valid) => {
        if (valid && (JSON.stringify(this.updateForm) !== this.oldData)) {
          this.$ajax.post('/goods/manage/modify/category', this.updateForm)
            .then(res => {
              if (res.data.success) {
                this.$Message.success('修改成功')
                this.initData()
              }
            })
        }
      })
    },
    removeClassify (data) {
      let str = '你确认删除' + data.name + '分类吗?'
      if (data.children) {
        str = '你确认删除' + data.name + '一级分类分类吗?（包括下面的子分类）'
      }
      let _self = this
      this.$Modal.confirm({
        title: '警告',
        content: str,
        onOk: () => {
          _self.sureDelete(data.id)
        }
      })
    },
    sureDelete (id) {
      this.$ajax.get('/goods/manage/remove/goods/category?categoryId=' + id)
        .then(res => {
          if (res.data.success) {
            this.$Message.success('删除成功')
            this.initData()
          }
        })
    },
    appendFirstClassify (data) {
      this.modal = true
      this.nodeData = data
    },
    subAddClassify () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let pid = this.nodeData.id
          if (!this.nodeData.id) {
            pid = 0
          }
          let params = {
            name: this.form.name,
            description: this.form.description,
            sortWeight: this.form.sortWeight,
            parentId: pid,
            status: '1'
          }
          if (pid === 0) {
            delete params.parentId
          }
          this.$ajax.post('/goods/manage/add/category', JSON.stringify(params)).then((res) => {
            if (res.data.success) {
              this.initData()
              this.$Message.success('添加分类成功')
              this.$refs.form.resetFields()
            }
          })
        } else {
          this.$Message.error('请正确填写表单信息')
          this.$nextTick(() => {
            this.modal = true
          })
        }
      })
    },

    getUnits () {
      /*
      * 获取全部单位
      * /goods/manage/get/unit/list
      * */
      this.$ajax.get('/goods/manage/get/unit/list')
        .then(res => {
          if (res.data.success) {
            this.units = res.data.data
          }
        })
    },
    getLabels () {
      /*
      * 获取全部标签
      * /goods/manage/get/goods/label/list
      * */
      this.$ajax.get('/goods/manage/get/goods/label/list')
        .then(res => {
          if (res.data.success) {
            this.labels = res.data.data
          }
        })
    },

    addUnit () {
      let value = ''
      this.$Modal.confirm({
        render: (h) => {
          return h('Input', {
            props: {
              autofocus: true,
              placeholder: '输入商品单位，如：个、件、套...'
            },
            on: {
              input: (val) => {
                value = val
              }
            }
          })
        },
        onOk: () => {
          this.$ajax.post('/goods/manage/add/unit/page', {unit: value}).then((res) => {
            if (res.data.success) {
              this.units.push({
                id: res.data.data.id,
                unit: res.data.data.unit
              })
              this.$Message.success('添加成功')
            }
          })
        }
      })
    },
    addLabel () {
      let value = ''
      this.$Modal.confirm({
        render: (h) => {
          return h('Input', {
            props: {
              autofocus: true,
              placeholder: '输入商品标签，如：古典、时尚、热卖...'
            },
            on: {
              input: (val) => {
                value = val
              }
            }
          })
        },
        onOk: () => {
          this.$ajax.post('/goods/manage/add/label/page', {label: value}).then((res) => {
            if (res.data.success) {
              this.labels.push({
                id: res.data.data.id,
                label: res.data.data.label
              })
              this.$Message.success('添加成功')
            }
          })
        }
      })
    },

    updateUnit (id, unit) {
      /*
      * 更新单位
      * params: id, unit
      * /goods/manage/modify/unit
      * */
      let value = unit
      this.$Modal.confirm({
        render: (h) => {
          return h('Input', {
            props: {
              autofocus: true,
              placeholder: '输入商品单位，如：个、件、套...',
              value
            },
            on: {
              input: (val) => {
                value = val
              }
            }
          })
        },
        onOk: () => {
          this.$ajax.post('/goods/manage/modify/unit', {id, unit: value}).then((res) => {
            if (res.data.success) {
              this.getUnits()
              this.$Message.success('修改成功')
            }
          })
        }
      })
    },
    updateLabel (id, label) {
      /*
      * 更新单位
      * params: id, unit
      * /goods/manage/modify/unit
      * */
      let value = label
      this.$Modal.confirm({
        render: (h) => {
          return h('Input', {
            props: {
              autofocus: true,
              placeholder: '输入商品标签，如：古典、时尚、热卖...',
              value
            },
            on: {
              input: (val) => {
                value = val
              }
            }
          })
        },
        onOk: () => {
          this.$ajax.post('/goods/manage/modify/goods/label', {id, label: value}).then((res) => {
            if (res.data.success) {
              this.getLabels()
              this.$Message.success('修改成功')
            }
          })
        }
      })
    },

    delUnit (id) {
      /*
      * 删除单位
      * params: id
      * */
      this.$Modal.confirm({
        title: '删除单位',
        content: '你确定删除该单位吗？',
        onOk: () => {
          this.$ajax.get('/goods/manage/remove/goods/unit', {params: {unitId: id}})
            .then(res => {
              if (res.data.success) {
                this.getUnits()
                this.$Message.success('删除成功')
              }
            })
        }
      })
    },
    delLabel (id) {
      /*
      * 删除标签
      * params: id
      * */
      this.$Modal.confirm({
        title: '删除标签',
        content: '你确定删除该标签吗？',
        onOk: () => {
          this.$ajax.get('/goods/manage/remove/goods/label', {params: {labelId: id}})
            .then(res => {
              if (res.data.success) {
                this.getLabels()
                this.$Message.success('删除成功')
              }
            })
        }
      })
    },

    initData () {
      this.$ajax.get('/goods/manage/get/category/list').then((res) => {
        res.data.data.forEach((item, index) => {
          item.title = item.name
          item.expand = true
          item.render = this.first
          item.childCategoryList.forEach(child => {
            child.title = child.name
            child.render = this.second
          })
        })
        this.treeClassifyData[0].childCategoryList = res.data.data
      })
    }
  },
  created () {
    this.initData()
    this.getUnits()
    this.getLabels()
  }
}
</script>

<style scoped>
  .list{
    margin-top: 16px;
    overfloat: left;
  }
  .list li{
    float: left;
    margin-right: 10px;
    height: 30px;
    line-height: 30px;
    padding-left: 8px;
    padding-right: 16px;
    border: 1px solid #dddee1;
    border-radius: 2px;
    position: relative;
    margin-bottom: 16px;
  }
  .list li:nth-child(1){
    border: none;
    padding: 0;
  }
  .list li .icon_box{
    position: absolute;
    top: 2px;
    right: 2px;
    cursor: pointer;
    display: none;
  }
  .list li:hover .icon_box{
    display: inline-block;
  }
  .icon_box i{
    display: block;
  }
</style>
